package com.ruoyi.business.controller;

import com.ruoyi.business.domain.School;
import com.ruoyi.business.service.ISchoolService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.TestSession;
import com.ruoyi.business.service.ITestSessionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.business.domain.vo.TestSessionStudentScoreExportVO;
import com.ruoyi.business.domain.vo.BmiClassStatExportVO;
import com.ruoyi.business.domain.vo.ClassProjectStatExportVO;
import com.ruoyi.business.domain.vo.ClassTotalScoreStatExportVO;
import com.ruoyi.business.utils.WordReportUtil;
import com.ruoyi.business.domain.vo.SchoolTestReportVO;

/**
 * 测试场次Controller
 * 
 * @author lcz
 * @date 2025-02-20
 */
@Api(tags = "测试场次相关接口")
@RestController
@RequestMapping("/business/testSession")
public class TestSessionController extends BaseController
{
    @Autowired
    private ITestSessionService testSessionService;

    @Autowired
    private ISchoolService schoolService;

    /**
     * 查询测试场次列表
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:testSession:list')")
    @GetMapping("/list")
    public TableDataInfo list(TestSession testSession)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        testSession.setSchoolId(sysUser.getSchoolId());

        startPage();
        List<TestSession> list = testSessionService.selectTestSessionList(testSession);
        return getDataTable(list);
    }

    /**
     * 导出测试场次列表
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:testSession:export')")
    @Log(title = "测试场次", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TestSession testSession)
    {
        List<TestSession> list = testSessionService.selectTestSessionList(testSession);
        ExcelUtil<TestSession> util = new ExcelUtil<TestSession>(TestSession.class);
        util.exportExcel(response, list, "测试场次数据");
    }

    /**
     * 获取测试场次详细信息
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:testSession:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(testSessionService.selectTestSessionById(id));
    }

    /**
     * 新增测试场次
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:testSession:add')")
    @Log(title = "测试场次", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TestSession testSession)
    {
        return toAjax(testSessionService.insertTestSession(testSession));
    }

    /**
     * 修改测试场次
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:testSession:edit')")
    @Log(title = "测试场次", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TestSession testSession)
    {
        return toAjax(testSessionService.updateTestSession(testSession));
    }

    /**
     * 删除测试场次
     */
    @ApiIgnore
//    @PreAuthorize("@ss.hasPermi('business:testSession:remove')")
    @Log(title = "测试场次", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(testSessionService.deleteTestSessionByIds(ids));
    }

    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/
    /** 前端接口 ***************************************************************************************************/

    /**
     * 某老师已结束测验列表
     * 接口路径：/testSession/front/list
     */
    @GetMapping("/front/endList")
    @ApiOperation("某老师已结束测验列表")
    public R<List<TestSession>> frontEndList()
    {
        return testSessionService.frontEndList();
    }

    /**
     * 某老师待开始测验列表
     * 接口路径：/testSession/front/list
     */
    @GetMapping("/front/startList")
    @ApiOperation("某老师待开始测验列表")
    public R<List<TestSession>> frontStartList()
    {
        return testSessionService.frontStartList();
    }

    /**
     * 获取测试场次详细信息
     * 接口路径：/testSession/front/info
     */
    @ApiOperation("前台获取测试场次详细信息")
    @GetMapping(value = "/front/info")
    public R<TestSession> frontInfo(@RequestParam("id") Long id)
    {
        return R.ok(testSessionService.selectTestSessionById(id));
    }

    /**
     * 新增测试场次
     * 接口路径：/testSession/front/add
     */
    @ApiOperation("前台新增测试场次")
    @PostMapping("/front/add")
    public AjaxResult frontAdd(@RequestBody TestSession testSession)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        School school = schoolService.selectSchoolById(sysUser.getSchoolId());

        // 校验测试名称是否重复
        TestSession param = new TestSession();
        param.setTestName(testSession.getTestName());
        param.setSchoolId(sysUser.getSchoolId());
        if (testSessionService.selectTestSessionListByName(param).size() > 0) {
            return AjaxResult.error("测试名称重复");
        }

        testSession.setTeacherId(sysUser.getUserId());
        testSession.setSchoolId(sysUser.getSchoolId());
        testSession.setSchoolName(school.getSchoolName());
        // 转换为 LocalDate
        LocalDate localDate = testSession.getEndTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        // 获取当天的最后一秒时间
        LocalDateTime endOfDay = localDate.atTime(23, 59, 59);
        // 转换回 Date 对象
        Date endOfDayDate = Date.from(endOfDay.atZone(ZoneId.systemDefault()).toInstant());
        testSession.setEndTime(endOfDayDate);
        testSessionService.insertTestSession(testSession);
        return AjaxResult.success(testSession.getId());
    }

    /**
     * 修改测试场次
     * 接口路径：/testSession/front/edit
     */
    @ApiOperation("前台修改测试场次")
    @PostMapping("/front/edit")
    public AjaxResult frontEdit(@RequestBody TestSession testSession)
    {
        Long userId = SecurityUtils.getUserId();
        testSession.setTeacherId(userId);
        return toAjax(testSessionService.updateTestSession(testSession));
    }
//
//    /**
//     * 删除测试场次
//     * 接口路径：/testSession/front/delete
//     */
//    @ApiOperation("前台删除测试场次")
//    @GetMapping("/front/delete")
//    public AjaxResult frontRemove(@RequestParam Long[] ids)
//    {
//        return toAjax(testSessionService.deleteTestSessionByIds(ids));
//    }

    /**
     * 导出单次测试所有学生成绩明细
     * 接口路径：/testSession/exportStudentScores
     */
    @ApiOperation("导出单次测试所有学生成绩明细")
    @PostMapping("/exportStudentScores")
    public void exportStudentScores(@RequestParam Long testSessionId, HttpServletResponse response) {
        List<TestSessionStudentScoreExportVO> exportList = testSessionService.buildExportStudentScores(testSessionId);
        ExcelUtil<TestSessionStudentScoreExportVO> util = new ExcelUtil<>(TestSessionStudentScoreExportVO.class);
        util.exportExcel(response, exportList, "单次测试学生成绩明细");
    }

    /**
     * 导出BMI班级统计表格
     * 接口路径：/testSession/exportBmiClassStat
     */
    @ApiOperation("导出BMI班级统计表格")
    @PostMapping("/exportBmiClassStat")
    public void exportBmiClassStat(@RequestParam Long testSessionId, HttpServletResponse response) {
        List<BmiClassStatExportVO> exportList = testSessionService.buildBmiClassStatExport(testSessionId);
        ExcelUtil<BmiClassStatExportVO> util = new ExcelUtil<>(BmiClassStatExportVO.class);
        util.exportExcel(response, exportList, "BMI班级统计");
    }

    /**
     * 导出班级各科成绩统计表格
     * 接口路径：/testSession/exportClassProjectStat
     */
    @ApiOperation("导出班级各科成绩统计表格")
    @PostMapping("/exportClassProjectStat")
    public void exportClassProjectStat(@RequestParam Long testSessionId, HttpServletResponse response) {
        List<ClassProjectStatExportVO> exportList = testSessionService.buildClassProjectStatExport(testSessionId);
        ExcelUtil<ClassProjectStatExportVO> util = new ExcelUtil<>(ClassProjectStatExportVO.class);
        util.exportExcel(response, exportList, "班级各科成绩统计");
    }

    /**
     * 导出班级总成绩统计表格
     * 接口路径：/testSession/exportClassTotalScoreStat
     */
    @ApiOperation("导出班级总成绩统计表格")
    @PostMapping("/exportClassTotalScoreStat")
    public void exportClassTotalScoreStat(@RequestParam Long testSessionId, HttpServletResponse response) {
        List<ClassTotalScoreStatExportVO> exportList = testSessionService.buildClassTotalScoreStatExport(testSessionId);
        ExcelUtil<ClassTotalScoreStatExportVO> util = new ExcelUtil<>(ClassTotalScoreStatExportVO.class);
        util.exportExcel(response, exportList, "班级总成绩统计");
    }

    /**
     * 导出学校总体体测报告word文档
     * 接口路径：/testSession/exportSchoolReport
     */
    @ApiOperation("导出学校总体体测报告word文档")
    @PostMapping("/exportSchoolReport")
    public void exportSchoolReport(@RequestParam Long testSessionId, HttpServletResponse response) throws Exception {
        SchoolTestReportVO reportVO = testSessionService.buildSchoolTestReport(testSessionId);
        byte[] wordBytes = WordReportUtil.generateSchoolReportWord(reportVO);
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        response.setHeader("Content-Disposition", "attachment; filename=school_report.docx");
        response.getOutputStream().write(wordBytes);
    }
}
